package handle

import (
	"bufio"
	"errors"
	"io"
	"log"
	"os"
	"strings"
)

type FileIOH struct{}

func (h *FileIOH) ConvertAndWrite(path *string) error {
	srcPath := "demo.bak"
	srcFile, err := h.OpenFile(&srcPath, os.O_RDONLY)
	if err != nil {
		log.Print(err)
		os.Exit(1)
	}

	sqlH := &SqlH{}
	res, err := sqlH.Handle()
	if err != nil {
		return err
	}

	for k, v := range res {

	}

	tarFile, err := h.OpenFile(path, os.O_APPEND|os.O_CREATE)
	if err != nil {
		log.Print(err)
		os.Exit(1)
	}
	defer func() {
		if err := srcFile.Close(); err != nil {
			log.Println(err)
			os.Exit(1)
		}
		if err := tarFile.Close(); err != nil {
			log.Println(err)
			os.Exit(1)
		}
	}()

	reader := bufio.NewReader(srcFile)
	for {
		line, _, err := reader.ReadLine()
		if err == io.EOF {
			break
		}
		//srcStr:= string(line)
		println(string(line))
		str := string(line)
		if strings.Contains(str, "$ENTITY$") {
			strings.ReplaceAll(str, "$ENTITY$", res["$ENTITY$"])
		}
	}
	return nil
}

func (h *FileIOH) Writer(path *string, s *string) error {
	file, err := h.OpenFile(path, os.O_APPEND)
	if err != nil {
		return err
	}
	defer func() {
		if err := file.Close(); err != nil {
			log.Println(err)
			os.Exit(1)
		}
	}()

	write := bufio.NewWriterSize(file, 4096)
	buf := []byte(*s)

	if _, err := write.Write(buf); err == nil {
		if err := write.Flush(); err != nil {
			os.Exit(1)
		}
	} else {
		os.Exit(1)
	}

	return nil
}

func (h *FileIOH) OpenFile(path *string, mode int) (*os.File, error) {
	if path == nil {
		return nil, errors.New("文件名不能为空")
	}
	file, err := os.OpenFile(*path, mode, 0644)
	if err != nil {
		return nil, err
	}
	return file, nil

}
